from django.core.urlresolvers import reverse
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.sites.models import Site
from django.contrib.syndication.feeds import Feed
from django.utils.feedgenerator import Atom1Feed
from django.conf import settings

from models import Release, Project, Poll

class RecentReleasesRSS(Feed):
    categories = ("python", "pygame", "open source", "game", "project",
                  "release", "version")
    description_template = 'projects/feeds/release_description.html'
    

    def items(self, obj):
        releases = Release.objects.order_by('-created')
        if obj:
            releases = releases.filter(project__id__exact=obj.id)
        return (releases.count() > settings.RECENT_RELEASES_FEED_OBJECTS and
                releases[:settings.RECENT_RELEASES_FEED_OBJECTS] or releases)
                                       
    def item_author_name(self, item):
        return item.creator.get_profile().display_name
    
    def item_author_link(self, item):
        return "/profiles/%s/" % item.creator.username
    
    def item_pubdate(self, item):
        return item.created

    def get_object(self, args):
        if len(args) > 1:
            raise ObjectDoesNotExist
        if not args:
            return
        return Project.objects.get(slug__exact=args[0])

    def title(self, obj):
        if obj:
            return "Recent Releases of %s" % obj
        return "%s - Recent Releases" % Site.objects.get_current()

    def link(self, obj):
        if not obj:
            return "/projects/latest/"
        return obj.get_absolute_url()

    def description(self, obj):
        if not obj:
            # all releases
            return "Recent releases of projects at %s" % Site.objects.get_current()
        # releases for a certain project
        return obj.summary


class RecentReleasesAtom(RecentReleasesRSS):
    feed_type = Atom1Feed
    subtitle = RecentReleasesRSS.description
    
    
class LatestPotmEntriesRSS(Feed):
    title = "%s projects of the moth" % Site.objects.get_current()
    description = "Latest projects of the month on %s" % Site.objects.get_current()
    title_template = 'projects/feeds/poll_title.html'
    description_template = 'projects/feeds/poll_description.html'
    def items(self):
        x = settings.POTM_FEED_OBJECTS
        q = Poll.objects.filter(active=False)
        return q.count() > x and q.all()[:x] or q.all()
    
    def link(self):
        return reverse("potm-overview")

class LatestPotmEntriesAtom(LatestPotmEntriesRSS):
    feed_type = Atom1Feed
    subtitle = LatestPotmEntriesRSS.description